﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;

namespace QQ2564874169.RelationalSql
{
    public interface IMultipleReader : IDisposable
    {
        IEnumerable<T> Read<T>();
        event EventHandler Disposed;
    }

    internal class MultipleReader: IMultipleReader
    {
        private bool _readed;
        private SqlDataReader _reader;
        public event EventHandler Disposed;

        internal MultipleReader(SqlDataReader reader)
        {
            _reader = reader;
        }

        public void Dispose()
        {
            _reader.Close();
            _reader.Dispose();
            _reader = null;
            Disposed?.Invoke(this, new EventArgs());
            Disposed = null;
        }

        public IEnumerable<T> Read<T>()
        {
            if (_readed)
            {
                _reader.NextResult();
            }
            else
            {
                _readed = true;
            }
            return _reader.ToArray<T>();
        }
    }
}
